<template>
  <view class="container">
    <view class="progress-container">
      <view class="progress-bar">
        <view class="progress" :style="{ width: `${progress}%` }" />
      </view>
      <text class="progress-text">{{ progress }}%</text>
    </view>

    <view class="question-container" v-if="!showResult">
      <view class="question-card">
        <view class="question-number">问题 {{ currentQuestion + 1 }}/{{ questions.length }}</view>
        <view class="question-content">{{ questions[currentQuestion].question }}</view>

        <view v-if="questions[currentQuestion].type == 'age'" class="age-picker">
          <picker mode="selector" :range="ageRange" @change="onAgeChange">
            <view class="picker-content">
              <text>{{ selectedAge || '请选择年龄' }}</text>
              <text class="picker-arrow">▼</text>
            </view>
          </picker>
        </view>

        <view v-else class="options">
          <view v-for="(option, index) in questions[currentQuestion].options" :key="index" class="option"
            :class="{ selected: selectedOption === index }" @click="selectOption(index)">
            <view class="option-circle">{{ ['A', 'B', 'C', 'D', 'E'][index] }}</view>
            <text>{{ option }}</text>
          </view>
        </view>
      </view>

      <button class="next-btn" :class="{ active: isCurrentQuestionAnswered }" :disabled="!isCurrentQuestionAnswered"
        @click="nextQuestion">
        {{ currentQuestion === questions.length - 1 ? '查看结果' : '下一题' }}
      </button>
    </view>

    
  </view>
</template>

<script setup>
import {computed, onMounted, ref} from 'vue'
import request from '../../utils/request';

// 年龄范围（18-100）
const ageRange = Array.from({ length: 82 }, (_, i) => i + 18)
const selectedAge = ref(null)

const questions = ref([])

// 当前问题序号
const currentQuestion = ref(0)
// 当前问题选项
const selectedOption = ref(null)
// 是否显示结果
const showResult = ref(false)
// 已回答问题数量
const answeredQuestions = ref(0)
// 已回答问题+答案
const answers = ref([])
const requestData = ref({})

onMounted(async () => {
  uni.showLoading({
    title:"加载中"
  })
  try {
    const res = await request.get('/questions')
    res.data.map(item => {
      questions.value.push({
        type: item.type,
        question: item.content,
        options: JSON.parse(item.options)
      })
    })

    // 获取 tongue的五个特征
    requestData.value.tongueDiagnosisId = uni.getStorageSync('tongueDescription').id;
	uni.removeStorageSync('tongueDescription')
  } catch (error) {
    uni.showToast({
      title: error || '获取问题失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
})

const progress = computed(() => {
  return Math.round((answeredQuestions.value / questions.value.length) * 100)
})

const selectOption = (index) => {
  selectedOption.value = index
}

// 修改计算属性判断当前问题是否已回答
const isCurrentQuestionAnswered = computed(() => {
  const currentQ = questions.value[currentQuestion.value]
  return currentQ.type === 'age' ? selectedAge.value != null : selectedOption.value != null
})

// 年龄选择器的改变事件处理
const onAgeChange = (e) => {
  selectedAge.value = ageRange[e.detail.value]
}

// 修改 nextQuestion 函数
const nextQuestion = () => {
  if (currentQuestion.value < questions.value.length - 1) {
    // 保存答案
    answers.value.push({
      question: questions.value[currentQuestion.value].question,
      answer: questions.value[currentQuestion.value].type === 'age'
        ? selectedAge.value
        : questions.value[currentQuestion.value].options[selectedOption.value]
    })
    currentQuestion.value++
    answeredQuestions.value++
    // 重置选项
    if (questions.value[currentQuestion.value].type === 'choice') {
      selectedOption.value = null
    }
  } else {
    // 保存答案
    answers.value.push({
      question: questions.value[currentQuestion.value].question,
      answer: questions.value[currentQuestion.value].options[selectedOption.value]
    })

    // 输出答案
    getResult()
    answeredQuestions.value = questions.value.length
  }
}

const getResult = async () => {
  // 显示加载提示
  uni.showLoading({
    title: '正在分析...',
    mask: true,
  })
  
  try {
    requestData.value.answers = answers.value
    const result = await request.post('/evaluate/result', requestData.value)
    // 隐藏加载提示
    uni.hideLoading()
    uni.showToast({
    	title: '评估结果已保存',
    	icon: 'success',
    	duration: 3000
    })
	
	uni.setStorageSync("evaluateResult", result.data);
    
    // 跳转到结果页面并传递数据
    uni.reLaunch({
      url: '/pages/question/result'
    })
  } catch (error) {
    // 发生错误时也要隐藏加载提示
    uni.hideLoading()
    uni.showToast({
      title: error || '获取结果失败',
      icon: 'none'
    })
  }
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
  padding: 40rpx 30rpx;
}

.progress-container {
  margin-bottom: 40rpx;

  .progress-bar {
    height: 8rpx;
    background: rgba(0, 122, 255, 0.1);
    border-radius: 4rpx;
    overflow: hidden;

    .progress {
      height: 100%;
      background: linear-gradient(90deg, #007AFF, #00C6FF);
      transition: width 0.5s ease;
    }
  }

  .progress-text {
    font-size: 24rpx;
    color: #007AFF;
    margin-top: 10rpx;
  }
}

.question-card {
  background: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.05);

  .question-number {
    font-size: 28rpx;
    color: #007AFF;
    margin-bottom: 20rpx;
  }

  .question-content {
    font-size: 36rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 60rpx;
  }
}

.options {
  .option {
    display: flex;
    align-items: center;
    background: #f8f9fa;
    padding: 30rpx;
    border-radius: 15rpx;
    margin-bottom: 20rpx;
    transition: all 0.3s;

    &.selected {
      background: rgba(0, 122, 255, 0.1);
      border: 2rpx solid #007AFF;

      .option-circle {
        background: #007AFF;
        color: #fff;
      }
    }

    .option-circle {
      width: 60rpx;
      height: 60rpx;
      border-radius: 30rpx;
      background: #fff;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 20rpx;
      font-size: 28rpx;
      color: #666;
      border: 2rpx solid #ddd;
    }
  }
}

.next-btn {
  margin-top: 60rpx;
  background: #007AFF;
  color: #fff;
  height: 88rpx;
  line-height: 88rpx;
  border-radius: 44rpx;
  font-size: 32rpx;

  &:disabled {
    opacity: 0.5;
  }
}

.result-card {
  padding: 40rpx;
  background: #fff;
  border-radius: 20rpx;
  margin-top: 40rpx;

  .result-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 40rpx;

    .result-title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
    }

    .result-type {
      font-size: 32rpx;
      color: #007AFF;
      font-weight: bold;

      .type-label {
        margin-right: 10rpx;
      }

      .type-value {
        color: #007AFF;
      }
    }
  }

  .result-content {
    .result-desc {
      font-size: 28rpx;
      color: #666;
      line-height: 1.6;
      margin-bottom: 40rpx;

      .desc-title {
        font-weight: bold;
        margin-bottom: 20rpx;
      }

      .desc-content {
        line-height: 1.6;
      }
    }

    .suggestion {
      background: #f8f8f8;
      padding: 30rpx;
      border-radius: 15rpx;

      .suggestion-title {
        font-size: 30rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 20rpx;
      }

      .suggestion-list {
        .suggestion-item {
          display: flex;
          align-items: center;
          margin-bottom: 10rpx;

          .item-number {
            font-size: 28rpx;
            color: #666;
            margin-right: 10rpx;
          }

          .item-content {
            font-size: 28rpx;
            color: #666;
            line-height: 1.6;
          }
        }
      }
    }
  }
}

// 添加年龄选择器样式
.age-picker {
  .picker-content {
    background: #f8f9fa;
    padding: 30rpx;
    border-radius: 15rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .picker-arrow {
      color: #666;
      font-size: 24rpx;
    }
  }
}
</style>